package com.ccp.dev.system.listener;

import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.system.license.SysLicense;
import com.ccp.dev.system.service.SysUserService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Spring启动关闭监听器。
 */
@Component
public class StartupListner implements ServletContextListener {
	@Resource
	private JdbcTemplate jdbcTemplate;

	@Value("${server.imModel.load}")
	private Boolean loadIm = false;

	@Override
	public void contextInitialized(ServletContextEvent event) {
		Boolean validateLicense = false;
		try {
			//2019-11-15 jyq修改
			validateLicense = SysLicense.validateLicnese();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!validateLicense){
			LoggerFactory.getLogger(StartupListner.class).error("The license on this server is expired.");
			LoggerFactory.getLogger(StartupListner.class).error("Please check the license on the server.");
			System.exit(0);
		}
		/*
		 * 服务启动重新初始化用户在线状态以及ip  以及 如果拥有im模块 将im模块得用户在线状态更新为离线
		 */
		SysUserService sysUserService = AppUtil.getBean(SysUserService.class);
		sysUserService.userStatusInit();
		if(loadIm){
			String sql = "update "+SystemConst.IM_CONNECTION_TABLE+" set status = 'offline'";
			jdbcTemplate.execute(sql);
		}
	}
}
